<template>
  <div>
    <div>
      <el-select size="small" v-model="listQuery.param.createUser" clearable placeholder="请选择">
        <el-option v-for="item in userRole" :key="item.userId" :label="item.userName" :value="item.userId">
          <span :class="{lineThrough:item.status === 100}" style="float: left">{{ item.userName }}</span>
          <span style="float: right; color: #8492a6; font-size: 13px">{{ item.roles }}</span>
        </el-option>
      </el-select>
      <el-select size="small" style="margin-left:10px;" v-model="listQuery.param.status" clearable placeholder="请选择">
        <el-option label="未审批" :value="0" />
        <el-option label="同意" :value="1" />
        <el-option label="拒绝" :value="100" />
      </el-select>
      <el-button size="small" type="primary" icon="el-icon-search" style="margin-left:10px;" @click="handleFilter">
        查询
      </el-button>
      <el-button v-if="add_project_file_button_status" size="small" icon="el-icon-plus" style="margin-left:10px;" @click="handleAdd">
        增加
      </el-button>
    </div>

    <el-table :data="fileList">
      <el-table-column v-if="false" prop="id" />
      <el-table-column v-if="false" prop="filePath" />
      <el-table-column prop="name" label="名称" show-overflow-tooltip width="200" />
      <el-table-column prop="desc" label="描述" show-overflow-tooltip width="200" />
      <el-table-column prop="createUser" label="创建人" width="200" />
      <el-table-column prop="createTime" label="创建时间" width="200" />
      <el-table-column prop="auditUser" label="审核人" width="200" />
      <el-table-column prop="auditTime" label="审核时间" width="200" />
      <el-table-column prop="auditComment" label="审核备注" show-overflow-tooltip width="200" />
      <el-table-column label="审核结果" width="100" fixed="right">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 0">未审批</el-tag>
          <el-tag v-if="scope.row.status === 1" type="success">同意</el-tag>
          <el-tag v-if="scope.row.status === 100" type="danger">拒绝</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="200" v-if="download_project_file_button_status || upd_project_file_button_status || del_project_file_button_status || audit_project_file_button_status">
        <template slot-scope="scope">
          <el-popover trigger="click" placement="left" width="130">
            <el-button style="margin-left:10px;" size="small" icon="el-icon-view" @click="handlePreview(scope.row)">预览文件</el-button>
            <el-button style="margin-left:10px;margin-top:5px;" v-if="download_project_file_button_status" size="small" icon="el-icon-download" type="info" @click="handleDownload(scope.row)">下载文件</el-button>
            <el-button style="margin-left:10px;margin-top:5px;" v-if="upd_project_file_button_status" size="small" icon="el-icon-edit" type="primary" :disabled="scope.row.status !== 0" @click="handleEdit(scope.row)">修改</el-button>
            <el-button style="margin-left:10px;margin-top:5px;" v-if="del_project_file_button_status" size="small" icon="el-icon-delete" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            <el-button slot="reference" icon="el-icon-setting" size='mini'>操作</el-button>
          </el-popover>

          <el-popover v-if="audit_project_file_button_status" trigger="click" placement="left" width="160" :ref="'popover' + scope.row.id" @after-leave="auditHide('audit' + scope.row.id)">
            <el-form :model="auditForm" :ref="'audit' + scope.row.id">
              <el-form-item prop="status">
                <el-select v-model="auditForm.status">
                  <el-option label="通过" :value="true" />
                  <el-option label="拒绝" :value="false" />
                </el-select>
              </el-form-item>
              <el-form-item prop="comment">
                <el-input placeholder="意见" v-model="auditForm.comment" />
              </el-form-item>
            </el-form>
            <div style="text-align: right; margin: 0">
              <el-button type="primary" size="mini" @click="auditFromSubmit('audit' + scope.row.id, scope.row.id)">确定</el-button>
            </div>
            <el-button slot="reference" :disabled="scope.row.status !== 0" style="margin-left:10px" type="primary" icon="el-icon-edit" size='mini'>审核</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[10, 20, 40, 100]" :page-size="listQuery.size" layout="total, sizes, prev, pager, next, jumper" :total="totalPreFinalAccountCount">
    </el-pagination>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="45%" :before-close="handleCancel">
      <el-form :rules="rules" :model="form" ref="form" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input v-model="form.desc" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="文件" prop="filePath">
          <el-upload action="" :show-file-list="false" :before-upload="beforeUploadFile" :http-request="uploadFile">
            <el-button size="small" type="primary">点击上传</el-button>
            <span>{{ form.filePath }}</span>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align:center;">
        <el-button @click="handleCancel()">
          取 消
        </el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="handleCreate()">
          确 定
        </el-button>
        <el-button v-if="dialogStatus=='update'" type="primary" @click="handleUpdate()">
          确 定
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>

import { mapGetters } from 'vuex';
import {
  saveFile, addPreFinalAccountFile, updPreFinalAccountFile, getPreFinalAccountFile, delPreFinalAccountFile, auditPreFinalAccountFile
} from '@/api/projectPreFinalAccountFile'
import { getAllProjectUserInfo } from '@/api/projectUserInfo'
import { preFinalAccountFileUploadUrl } from '@/utils'

export default {
  name: 'ProjectPreFinalAccountFilePage',
  props: {
    ProjectId: {
      type: Number
    }
  },
  watch: {
    ProjectId(newVal, oldVal) {
      console.log("PreFinalAccountFile old: " + oldVal + ", new: " + newVal + ", watch: " + this.isWatch);
      this.projectId = newVal;
      this.listQuery.param.projectId = newVal;
      this.form.projectId = newVal;
      if (newVal === 0) {
        this.fileList = [];
        this.totalPreFinalAccountCount = 0;
      }
      else if (this.isWatch) {
        this.getAllUserRoleInfo();
        this.getPreFinalAccountFileList();
      }
    }
  },
  computed: {
    ...mapGetters(["elements"])
  },
  created() {
    if (this.elements['add_project_file']) {
      this.add_project_file_button_status = true;
    }
    if (this.elements['upd_project_file']) {
      this.upd_project_file_button_status = true;
    }
    if (this.elements['del_project_file']) {
      this.del_project_file_button_status = true;
    }
    if (this.elements['audit_project_file']) {
      this.audit_project_file_button_status = true;
    }
    if (this.elements['download_project_file']) {
      this.download_project_file_button_status = true;
    }
  },
  data() {
    return {
      textMap: {
        create: "创建",
        update: "修改"
      },
      dialogFormVisible: false,
      dialogStatus: "",

      projectId: 0,
      userRole: [],
      listQuery: {
        page: 1,
        size: 10,
        param: {
          projectId: undefined,
          createUser: undefined,
          status: undefined
        }
      },
      fileList: [],

      form: {
        id: undefined,
        projectId: undefined,
        name: undefined,
        desc: undefined,
        filePath: undefined
      },
      rules: {
        name: [
          { required: true, message: "请填写名称", trigger: "blur" },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        desc: [
          { min: 1, max: 250, message: '长度在 1 到 250 个字符', trigger: 'blur' }
        ],
        filePath: [
          { required: true, message: '请上传文件', trigger: 'blur' }
        ]
      },

      auditForm: {
        id: undefined,
        status: true,
        comment: undefined
      },
      isWatch: false,
      totalPreFinalAccountCount: undefined,

      add_project_file_button_status: false,
      upd_project_file_button_status: false,
      del_project_file_button_status: false,
      audit_project_file_button_status: false,
      download_project_file_button_status: false,
    }
  },
  mounted() {

  },
  methods: {
    show() {
      this.isWatch = true;
      if (this.projectId === 0) {
        this.fileList = [];
        this.totalPreFinalAccountCount = 0;
        return;
      }
      this.getAllUserRoleInfo();
      this.getPreFinalAccountFileList();
    },
    hide() {
      this.isWatch = false;
    },
    getAllUserRoleInfo() {
      getAllProjectUserInfo(this.projectId).then(resp => {
        this.userRole = resp.datas;
      });
    },
    getPreFinalAccountFileList() {
      getPreFinalAccountFile(this.listQuery).then(resp => {
        this.fileList = resp.datas.datas;
        this.totalPreFinalAccountCount = resp.datas.total;
      })
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getPreFinalAccountFileList();
    },
    // 文件上传
    uploadFile(d) {
      saveFile(d.file).then(resp => {
        this.form.filePath = resp.datas.filePath;
        if (!this.form.name) {
          this.form.name = resp.datas.name;
        }
      })
    },
    // 文件上传前检查
    beforeUploadFile(file) {
      return true;
    },
    handleAdd() {
      this.resetForm();
      this.dialogFormVisible = true;
      this.dialogStatus = 'create';
    },
    handleCreate() {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return false;
        }
        addPreFinalAccountFile(this.form).then(resp => {
          this.$notify({
            title: '成功',
            message: '增加成功',
            type: 'success',
            duration: 2000,
            customClass: 'notityClass'
          });
          this.handleCancel();
          this.handleFilter();
        })
      });
    },
    handleEdit(row) {
      this.resetForm();
      this.dialogFormVisible = true;
      this.dialogStatus = 'update';
      this.$nextTick(() => {
        this.form = {
          id: row.id,
          projectId: this.projectId,
          name: row.name,
          desc: row.desc,
          filePath: row.filePath
        };
      });
    },
    handleUpdate() {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return false;
        }
        updPreFinalAccountFile(this.form).then(resp => {
          this.$notify({
            title: '成功',
            message: '修改成功',
            type: 'success',
            duration: 2000,
            customClass: 'notityClass'
          });
          this.handleCancel();
          this.handleFilter();
        })
      })
    },
    handleDelete(row) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        delPreFinalAccountFile(row.id).then(resp => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000,
            customClass: 'notityClass'
          });
          this.handleFilter();
        })
      });
    },
    handleCancel() {
      this.dialogFormVisible = false;
      this.dialogStatus = undefined;
      this.resetForm();
    },
    handleDownload(row) {
      var a2 = document.createElement('a');
      a2.href = preFinalAccountFileUploadUrl(row.filePath);
      a2.setAttribute("download", "true");
      a2.click();
    },
    resetForm() {
      if (this.$refs["form"]) {
        this.$refs["form"].resetFields();
      }
    },
    auditHide(formname) {
      this.$refs[formname].resetFields();
    },
    auditFromSubmit(formname, id) {
      this.auditForm.id = id;
      auditPreFinalAccountFile(this.auditForm).then(resp => {
        console.log("auditPreFinalAccountFile resp", resp);
        this.$notify({
          title: "成功",
          message: "审批成功",
          type: "success",
          duration: 2000
        });
        this.$refs['popover' + id].doClose();
        this.getPreFinalAccountFileList();
      })
    },
    handleSizeChange(val) {
      this.listQuery.size = val;
      this.getPreFinalAccountFileList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getPreFinalAccountFileList();
    },
    handlePreview(row) {
      var src = "https://view.officeapps.live.com/op/view.aspx?src=" + encodeURIComponent(preFinalAccountFileUploadUrl(row.filePath));
      window.open(src);
    }
  }
}
</script>